/**
 * 自定义地图经纬度控件
 */

import { bindAll, extend } from './control-utils'
import '@/components/gis/map-package/map-controls/map-control-style.less'

/**
 * 更新经纬度信息
 * @param map
 * @param container
 * @param $event
 * @param options
 */
function updateCoordinate(
  map: any,
  container: any,
  $event: any,
  options: Options
) {
  const { decimal } = options
  const lng: number = $event.lngLat.lng.toFixed(decimal)
  const lat: number = $event.lngLat.lat.toFixed(decimal)
  container.textContent = `纬度: ${lat} 经度: ${lng}`
}

interface Options {
  decimal?: number
}

const defaultOptions: Options = {
  decimal: 3,
}

/**
 * CoordinatesControl class
 */

export default class CoordinatesControl {
  _map: any
  _container: any
  options: Options

  constructor(options: Options) {
    this.options = extend({}, defaultOptions, options)
    this._container = document.createElement('div')
    this._container.className = 'mapboxgl-ctrl  mapboxgl-ctrl-coordinates'
    this._container.textContent = '纬度: 0 经度: 0'
    bindAll(['_onMouseMove'], this)
  }

  /**
   * 鼠标移动的事件
   * @param $event
   */
  public _onMouseMove($event: any) {
    updateCoordinate(this._map, this._container, $event, this.options)
  }

  onAdd(map: any) {
    this._map = map
    this._map.on('mousemove', this._onMouseMove)
    return this._container
  }

  onRemove() {
    // this._container.parentNode.removeChild(this._container)
    this._container.remove()
    this._map.off('move', this._onMouseMove)
    this._map = undefined
  }
}
